package scheduler

import (
    "crawler/engine"
)

type QueuedScheduler struct {
    requestChan engine.RequestChan
    workerChan  chan engine.RequestChan
}

func (q *QueuedScheduler) WorkerChan() engine.RequestChan {
    return make(engine.RequestChan)
}

func (q *QueuedScheduler) WorkerReady(c engine.RequestChan) {
    q.workerChan <- c
}

func (q *QueuedScheduler) Run() {
    q.requestChan = make(engine.RequestChan)
    q.workerChan = make(chan engine.RequestChan)
    go func() {
        var requestQ []engine.Request
        var workerQ []engine.RequestChan
        for {
            var activeReq engine.Request
            var activeWorker engine.RequestChan
            if len(requestQ) != 0 &&
                len(workerQ) != 0 {
                activeReq = requestQ[0]
                activeWorker = workerQ[0]
            }
            select {
            case req := <-q.requestChan:
                requestQ = append(requestQ, req)
            case worker := <-q.workerChan:
                workerQ = append(workerQ, worker)
            case activeWorker <- activeReq:
                requestQ = requestQ[1:]
                workerQ = workerQ[1:]
            }
        }
    }()
}

func (q *QueuedScheduler) Submit(req engine.Request) {
    q.requestChan <- req
}
